package com.itheima.springbootwebtlias.filter;

import com.itheima.springbootwebtlias.util.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;

import java.io.IOException;

@Slf4j
//@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1.获取请求路径
        String url = request.getRequestURI().toString();

        //2.判断请求路径是否为登录请求
        //如果为登录请求，直接放行
        if (url.contains("/login")) {
            log.info("登录请求，直接放行");
            filterChain.doFilter(request, response);
            return;  //return 不能省略
        }

        //3.获取请求头中的令牌
        String jwt = request.getHeader("token");
        if (jwt == null){
            log.info("请求头中没有令牌,请登录... ...");
            //没有携带令牌，封装错误结果
            response.setStatus(HttpStatus.SC_UNAUTHORIZED); //401
            //response.setStatus(401);
            return;   //return 不能省略
        }

        //4.解析令牌，判断令牌是否正确
          try {
              JwtUtils.parseJWT(jwt);  //依靠工具类解析令牌
          }   catch (Exception e){
              log.info("令牌解析错误，请重新登录... ...");
              //解析错误，封装错误结果
              response.setStatus(HttpStatus.SC_UNAUTHORIZED); //401
              return; //return 不能省略
          }

          //5.放行
        log.info("令牌解析正确，放行... ...");
          filterChain.doFilter(request, response);
    }
}
